<template>
  <el-dialog v-loading="loading" center title="ئۇچۇرلار" :visible.sync="dialogVisible" width="width" :before-close="dialogBeforeClose" :destroy-on-close="true">
    <el-form ref="form" :model="form" :rules="ruleForm" label-width="120px">
      <el-form-item label="ئىسمى:" prop="title">
        <el-row>
          <el-col :span="12">
            <el-input size="small" v-model="form.title" autocomplete="off"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="رەسىمى:" prop="coverImg">
        <!-- <img :src="info.coverImg" style="height:200px" alt=""> -->
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeAvatarUpload">
          <img v-if="form.coverImg" :src="form.coverImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <!-- <el-button type="primary" v-if="imgFile">رەسىم ئادىرىسگە ئېرىشىش</el-button> -->
      </el-form-item>
      <el-form-item label="جەمئىي قىسىم:" prop="total_qisim">
        <el-row>
          <el-col :span="4">
            <el-input size="small" v-model="form.total_qisim" autocomplete="off"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="تىپى:" prop="type">
        <el-row>
          <el-col :span="12">
            <el-select size="small" v-model="form.type" placeholder="">
              <el-option v-for="item in [{label:'كىنو فىلىم',value:1},{label:'كۆپ قىسىملىق',value:2}]" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="تۈرى:" prop="sort">
        <el-row>
          <el-select multiple size="small" v-model="form.sort" placeholder="">
            <el-option v-for="item in sortList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-row>
      </el-form-item>
      <el-form-item label="تەۋە دۆلەت:" prop="nation">
        <el-row>
          <el-col :span="12">
            <el-select size="small" v-model="form.nation" placeholder="">
              <el-option v-for="item in nationList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label=" تىل:" prop="lang">
        <el-row>
          <el-col :span="12">
            <el-select size="small" v-model="form.lang" placeholder="">
              <el-option v-for="item in langList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <div class="tips">
        <p>نورمال ئادىرىس: MP4,FLV, m3u8
          <!-- http://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/byted-player-videos/1.0.0/xgplayer-demo-720p.mp4 -->
        </p>
        <p>تېڭشۈن WXV : wxv_1632566864574775305</p>
      </div>
      <el-form-item label="قىسىملىرى：" prop="list">
        <el-table stripe :data="qisimList" style="max-height:50vh;overflow-y:scroll">
          <el-table-column align="center" prop="qisim" label="قىسىم سانى" width="160px">
            <template slot-scope="{$index}">
              <el-input v-model="qisimList[$index].qisim" size="small" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="url" label="كىنو ئادىرىسى">
            <template slot-scope="{$index}">
              <el-input v-model="qisimList[$index].url" size="small" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="url_type" label="ئادىرىس تىپى">
            <template slot-scope="{row}">
              <el-select size="small" v-model="row.url_type" placeholder="">
                <el-option v-for="item in [
                      {label:'نورمال ئادىرىس',value:1},
                      {label:'تېڭشۈن wxv',value:2},]" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="مەشغۇلات">
            <template slot-scope="{$index}">
              <el-button type="danger" size="small" v-if="qisimList.length!=1" @click="delCurrLine($index)">يۇيۇش</el-button>
              <el-button size="small" v-if="$index==qisimList.length-1" @click="createNewLine" type="primary" icon="el-icon-circle-plus-outline"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- <el-form-item label-width="0">
        <el-row style="margin-top:24px;text-align:center">
          <el-button type="primary" @click="uploadImg">قىسىمنى ساقلاش</el-button>
        </el-row>
      </el-form-item> -->
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">ئەمەلدىن قالدۇرۇش</el-button>
      <el-button type="primary" @click="saveVideoInfo">كىنو ئۇچۇرنى ساقلاش</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { LANG_MAP, NATION_MAP } from '@/utils/enums'
import { addNewVideo } from '@/api/kino';

export default {
  name: 'AddDialog',
  props: {
    sortList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {
        sort: []
      },
      dialogVisible: false,
      loading: false,
      nationMap: NATION_MAP,
      nationList: Object.keys(NATION_MAP).reduce((list, curr) => list.concat({ label: NATION_MAP[curr], value: Number(curr) }), []),
      imgFile: null,
      qisimList: [{ qisim: 1, url_type: 1 }],
      ruleForm: {
        coverImg: [{ required: true, message: 'كىنو رەسىمىنى چىقىرىڭ' }],
        title: [{ required: true, message: 'كىنو ئىسمىنى كىرگۈزۈڭ', trigger: 'blur' }],
        total_qisim: [{ required: true, message: 'قىسىم سانىنى كىرگۈزۈڭ', trigger: 'blur', min: 1 }, { pattern: /(\d)+/, message: 'پەقەت سانلا كىرگۈزگىلى بولىدۇ', trigger: 'blur' }],
      },
      langList: Object.keys(LANG_MAP).reduce((list, curr) => list.concat({ label: LANG_MAP[curr], value: Number(curr) }), [])
    };
  },
  /* created() {

  },
  mounted() {

  }, */
  methods: {
    dialogBeforeClose(done) {
      if (Object.keys(this.form).length > 1) {
        this.$confirm('ئۆچۈرگەندىن كىيىن تولدۇرغان ئۇچۇرلار يۇيۇلىدۇ ، جەزملەشتۈرەمسىز؟', {
          cancelButtonText: 'ياق',
          confirmButtonText: 'ھەئە'
        }).then(_ => {
          done()
        }).catch(_ => { })
      } else {
          done()
      }
    },
    playVideo(row) {
      let url;
      if (row.url_type == 1) {
        url = row.url
      } else if (row.url_type == 2) {
        // url = `https://mp.weixin.qq.com/mp/videoplayer?action=get_mp_video_play_url&preview=0&__biz=&mid=&idx=&vid=${row.url}&uin=&key=&pass_ticket=&wxtoken=&appmsg_token=&x5=0&f=json` //获取地址
        url = `https://mp.weixin.qq.com/mp/readtemplate?t=pages/video_player_tmpl&action=mpvideo&auto=0&vid=${row.url}`
      }
      window.open(url, '_blank')
      //   console.log(row);
    },
    saveVideoInfo() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          for (let [index, item] of this.qisimList.entries()) {
            if (!item.qisim || !item.url_type || !item.url) {
              this.$message.error(`${index + 1} -قۇرنى تۇللۇق كىرگۈزمەپسىز`);
              return;
            }
          }
          try {
            this.loading = true;
            let coverImg = await this.uploadImg()
            let { sort, total_qisim } = this.form;
            let form = {
              vid: Date.now().toString(36) + (Math.random().toString().slice(2, 6)).toString(36),
              ...this.form,
              total_qisim: Number(total_qisim),
              coverImg,
              sort: sort.length ? JSON.stringify(sort) : null,
              qisimList: this.qisimList
            };
            addNewVideo(form).then(res => {
              this.$message.success('كىنو چىقىرىلدى');
              this.$emit('getList');
              this.dialogVisible = false;
              this.loading = false;

            }).catch(err => {
              this.loading = false;

            })
            console.log(form);
            /* this.$confirm('ساقلاشنى جەزملەشتۈرەمسىز؟', {
              cancelButtonText: 'ياق',
              confirmButtonText: 'ھەئە'
            }).then(_ => {
              this.loading = true
              updateVideoInfo(info).then(res => {
                if (res.affectedRows) {
                  this.$message.success('ساقلاندى');
                  this.$emit('getList');
                }
                this.loading = false
              }).catch(err => {
                this.loading = false
              })
              // console.log(info);
            }).catch(_ => { }) */
          } catch (error) {
            this.$message.error(error)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    uploadImg() {
      return new Promise((resolve, reject) => {
        var cos = new COS({
          SecretId: 'AKID1sTnqc8MJ0QedLnysUqvjGWWFgtqZ2D8',
          SecretKey: 'f28yXppZ3GDsHSMzMSIsBDySeaEbhW5N',
        });
        let self = this;
        this.$loading();
        cos.putObject({
          Bucket: 'qaplan-1252253374', /* 必须 */
          Region: 'ap-shanghai',     /* 存储桶所在地域，必须字段 */
          Key: `/AppImg/${this.$store.state.user.name || 'Yusup'}/` + Date.now().toString(36) + (Math.random().toString().slice(2, 10) * 1000).toString(32) + '.' + self.imgFile.type.split('/')[1],              /* 必须 */
          StorageClass: 'STANDARD',
          Body: this.imgFile, // 上传文件对象
          onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
          }
        }, function (err, data) {
          self.$loading().close();
          if (err) {
            self.$message.error(err);
            reject();
          } else {
            if (data.statusCode == 200) {
              let imgUrl = data.Location.replace('qaplan-1252253374.cos.ap-shanghai.myqcloud.com', 'https://cdn.qolayapp.cn')
              // self.form.coverImg = data.Location.replace('qaplan-1252253374.cos.ap-shanghai.myqcloud.com', 'https://cdn.qolayapp.cn')
              self.$message.success('رەسىم چىقىرىلدى')
              resolve(imgUrl)
            } else {
              reject
            }
          }
          // console.log(err || data);
        });
      })
    },
    beforeAvatarUpload(file) {
      //   console.log(...arguments);
      let blob = new Blob([file], { type: file.type });
      let tempUrl = URL.createObjectURL(blob);
      this.$set(this.form, 'coverImg', tempUrl)
      this.imgFile = file;
      return false
    },
    createNewLine() {
      this.qisimList.push({ qisim: this.qisimList.length + 1, url_type: 1 })
    },
    delCurrLine(index) {
      this.qisimList.splice(index, 1)
    }
  },
  watch: {
    /* 'form.total_qisim': {
      handler(val) {
        if (this.qisimList.length != val) {
          let diff = Math.abs(val - this.qisimList.length);
          if (this.qisimList.length < val) {
            for (let i = 0; i < diff; i++) {
              this.qisimList.push({ qisim: this.qisimList.length + 1, url_type: 1 })
            }
          } else {
            this.qisimList.splice(val, diff)
          }
        }
      }
    } */
  }
};
</script>

<style  lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.tips {
  text-align: center;
}
</style>
